package com.clstu.enum_.homework;

public class HomeWork05 {
    public static void main(String[] args) {
        Person person = new Person("唐僧", Factory.getHorse());//相当于把工厂里的马拿来用
        System.out.println("一班情况下");
        person.common();
        System.out.println("遇到大河的情况下");
        //person.setV(Factory.getBoat());//把工厂里的船拿来用 这样写扩展性不如多写两个方法（passriver，common）可扩展性高
        person.passRiver();
        System.out.println("前方火焰山");
        person.FlyMountain();
    }
}
interface Vehicle{
    void work();
}

class Horse implements Vehicle{
    @Override
    public void work() {
        System.out.println("Horse can run in the field ...(骑马)");
    }
}

class Boat implements Vehicle{
    @Override
    public void work() {
        System.out.println("Boat can pass a river ...（坐船过河）");
    }
}

class Plain implements Vehicle{
    @Override
    public void work() {
        System.out.println("Air plain can flying ... (飞过去）");
    }
}

class Factory{
    private static Horse horse;//类似与懒汉式单例模式，不调用就不会产生对象
    private static Boat boat ;
    private static Plain plain;
    public static Horse getHorse(){
        if(horse==null){//这样判断也能规避v=null的情况
            horse= new Horse();
        }
        return horse;
    }
    public static Boat getBoat(){
        if(boat==null){
            boat= new Boat();
        }
        return boat;
    }

    public static Plain getPlain(){
        if(plain==null){
            plain=new Plain();
        }
        return plain;
    }
}

class Person{
    private String name;
    private Vehicle v;
    public Person(String name, Vehicle v) {
        this.name = name;
        this.v = v;
    }

    public Vehicle getV() {
        return v;
    }

    public void setV(Vehicle v) {//多态参数
        this.v = v;
    }
    public void common(){
        if(!(v instanceof Horse)){
            v=Factory.getHorse();
        }
        v.work();
    }

    public void passRiver(){
        if(!(v instanceof Boat)){
            v=Factory.getBoat();
        }
        v.work();
    }

    public void FlyMountain(){
        if(!(v instanceof Plain)){
            v=Factory.getPlain();
        }
        v.work();
    }
    public void useVehicle(){//动态绑定机制
        v.work();
    }
}